/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package yoga.algo.polygon;

import java.awt.Polygon;
import yoga.algo.coding.ICoding;
import yoga.algo.coding.IGenotypeCodec;
import yoga.algo.coding.binary.BinaryStringCoding;
import yoga.algo.coding.floating.FloatDataArray;
import yoga.algo.coding.floating.FloatingPointCoding;

/**
 *
 * @author Yogev Montekyo
 */
public class PolygonFloatingPointCodec implements IGenotypeCodec<Polygon>
{
    @Override
    public Polygon decode(ICoding<Polygon> coding) throws IllegalArgumentException
    {
        BinaryStringCoding<Polygon> binaryStringPolygonCoding;
        if (!(coding instanceof FloatingPointCoding))
        {
            throw new IllegalArgumentException("Type missmatch, " + FloatingPointCoding.class.getName() + " cannot decode following coding " + coding.getClass().getName());
        }

        Polygon polygon = new Polygon();
        FloatingPointCoding<Polygon> floatCoding = (FloatingPointCoding<Polygon>) coding;

        int coordinatesNumber = floatCoding.getNumberOfArguments();
        FloatDataArray floatDataArray = floatCoding.getData();

        int currentCoordinate = 0;
        while (currentCoordinate < coordinatesNumber * 2)
        {
            double x = floatDataArray.getFloat(currentCoordinate);
            double y = floatDataArray.getFloat(currentCoordinate + 1);
            currentCoordinate += 2;

            polygon.addPoint((int) x, (int) y);
        }

        return polygon;
    }

    @Override
    public FloatingPointCoding<Polygon> encode(Polygon polygon) throws IllegalArgumentException
    {
        int size = (int) polygon.npoints;
        FloatDataArray floatDataArray = new FloatDataArray(size * 2);

        int arrayIndex = 0;
        for (int coordinateIndex = 0; coordinateIndex < size; coordinateIndex++)
        {
            floatDataArray.setFloat(arrayIndex++, (double) polygon.xpoints[coordinateIndex]);
            floatDataArray.setFloat(arrayIndex++, (double) polygon.ypoints[coordinateIndex]);
        }
        
        FloatingPointCoding<Polygon> coding = new FloatingPointCoding(floatDataArray);
        coding.setNumberOfArguments(size);
        coding.setLowerBoundary(0);
        coding.setUpperBoundary(400);
        return coding;
    }
}
